<script setup lang='ts'>
defineOptions({ name: 'AppSportsPageSearch' })

const { bool: isClear, setTrue: setClearTrue } = useBoolean(true)
const sportsStore = useSportsStore()

const searchValue = ref('')
const keywordSports = ref(
  Local.get<any[]>(STORAGE_SEARCH_KEYWORDS_SPORTS)?.value ?? [],
)
const currentSiTab = ref(0)

const goodSearchValue = computed(() => searchValue.value.length >= 3)

// 体育搜索接口
const { data: sportsData, run: runSearchSports, loading } = useRequest(
  () => ApiSportEventSearch({ word: searchValue.value }),
  {
    onBefore() {
      currentSiTab.value = 0
    },
    onSuccess(res) {
      if (res.list && res.list.length > 0) {
        currentSiTab.value = res.list[0].si
        const word = searchValue.value

        // 去重
        if (keywordSports.value.includes(word))
          keywordSports.value.splice(keywordSports.value.findIndex(t => t === word), 1)

        keywordSports.value.unshift(word)
        keywordSports.value = keywordSports.value.slice(0, 5)
        Local.set(STORAGE_SEARCH_KEYWORDS_SPORTS, keywordSports.value)
      }
    },
    onAfter() {
      isClear.value = false
    }
  },
)


// 搜索结果
const siTabs = computed(() => {
  if (isClear.value || !goodSearchValue.value)
    return null
  if (sportsData.value && sportsData.value.list && sportsData.value.list.length > 0) {
    return sportsData.value.list.map((a) => {
      return {
        label: a.sn,
        value: a.si,
        icon: sportsStore.getSportsIconBySi(a.si)
      }
    })
  }

  return null
})
const resultData = computed(() => {
  if (isClear.value || !goodSearchValue.value)
    return null
  if (sportsData.value && sportsData.value.list && sportsData.value.list.length > 0) {
    const dataFindBySi = sportsData.value.list.find(a => a.si === currentSiTab.value)
    if (dataFindBySi) {
      return dataFindBySi.list.map((b) => {
        return {
          ...b,
          leagueName: `${dataFindBySi.sn} ‧ ${b.pgn} ‧ ${b.cn}`,
          leaguePath: getSportsRoutePath({
            page: '/sport',
            si: `${dataFindBySi.si}`,
            ci: b.ci,
            cn: b.cn,
            pgid: b.pgid
          }),
          teamName: `${b.htn} - ${b.atn}`,
          teamPath: '',
          time: timeToDateWithDayFormat(b.ed),
        }
      })
    }
    return []
  }

  return null
})

let inputTimer: any = null
function onBaseSearchInput() {
  clearTimeout(inputTimer)
  if (searchValue.value.length < 3) {
    setClearTrue()
    return
  }
  inputTimer = setTimeout(() => {
    if (searchValue.value.length >= 3) {
      Local.set(STORAGE_CLEAR_SPORTS, true)
      runSearchSports()
    }
    clearTimeout(inputTimer)
  }, 500)
}

function onLeagueNameClick(item: any) {
  i18nNavigateTo(item.leaguePath)
}
</script>

<template>
  <div class="flex-1">
    <div class="flex items-center">
      <AppSportsSearchInput :loading="loading" :placeHolder="$t('search')" v-model.trim="searchValue"
        @input="onBaseSearchInput" @clear="setClearTrue" />
      <div @click="i18nNavigateTo('/sports?bt-path=%2F')"
        class="ml-[8px] cursor-pointer flex-none text-[var(--color-text-white-0)] text-[14px] leading-[16px] font-[590]">
        {{ $t('close') }}
      </div>
    </div>

    <!-- 有结果 -->
    <template v-if="resultData">
      <AppSportsTab v-if="siTabs" class="mb-[24px] mt-[16px]" v-model="currentSiTab" :list="siTabs" />
      <div class="w-full flex flex-col">
        <div v-for="item in resultData" :key="item.ei" class="not-last-of-type:mb-[20px] w-full flex flex-col">
          <div @click="onLeagueNameClick(item)"
            class="cursor-pointer w-full overflow-hidden whitespace-nowrap text-ellipsis">
            <span class="text-[var(--color-white-500)] font-bold text-[12px] leading-[12px]">
              {{ item.leagueName }}
            </span>
          </div>
          <span
            class="cursor-pointer mb-[8px] mt-[4.5px] text-[var(--color-text-white-0)] text-[18px] font-[590] leading-[18px]">
            {{ item.teamName }}
          </span>
          <span class="text-[var(--color-white-500)] text-[12px] font-bold leading-[12px]">
            {{ item.time }}
          </span>
        </div>
      </div>
    </template>


    <!-- 空状态 -->
    <div class="empty">
      <template v-if="isClear">
        <BaseIcon name="spt-search-banner" class="text-[110px]" />
        <div class="text">{{ $t('sports_search_des') }}</div>
      </template>
      <template v-if="!isClear && !resultData">
        <BaseIcon name="spt-search-empty" class="text-[110px]" />
        <div class="text">
          {{ $t('spt_search_empty') }}<br />
          {{ $t('spt_search_empty2') }}
        </div>
        <AppSportsBaseButton class="min-w-[176px] px-[28px] mt-[32px]" style="--bc-sports-base-button-height:32px;"
          @click="i18nNavigateTo('/sports?bt-path=%2F')">
          {{ $t('spt_go_home_page') }}
        </AppSportsBaseButton>
      </template>
    </div>
  </div>
</template>

<style lang='scss' scoped>
.empty {
  color: var(--color-text-white-0);
  display: flex;
  align-items: center;
  padding-top: 48px;
  flex-direction: column;

  .text {
    font-size: 18px;
    max-width: 400px;
    margin-top: 32px;
    text-align: center;
    line-height: 28px;
    letter-spacing: 0.4px;
  }
}
</style>
